﻿/// <Summary> 
/// $Author: Nikhil Chinchwade 
/// Azure Monitoring Configuration

/// $Creation Date : 
/// </summary>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MindTree.PerfWorkbench.Azure.Monitor.Core;
using System.Reflection;
using System.Windows.Markup;

namespace MindTree.PerfWorkbench.Azure.Monitor
{
    /// <summary>
    /// Interaction logic for AzMonConfig.xaml
    /// </summary>
    public partial class AzMonConfig : Window
    {
        public Boolean IsOK = false;

        public IList<PerfCounter> modifiedCounters = new List<PerfCounter>();

        public IList<CounterSet> newCounterSetList = new List<CounterSet>();

        private bool isModified = false;

        public AzMonConfig()
        {
            InitializeComponent();
            GenerateConfigurationGridView();
        }

        private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem)
                {
                    return (childItem)child;
                }
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null)
                    {
                        return childOfChild;
                    }
                }
            }
            return null;
        }


        /// <summary>
        /// Dynamically generate the GUI
        /// </summary>
        private void GenerateConfigurationGridView()
        {
           
            FrameworkElementFactory cellTemplateFactory1 = new FrameworkElementFactory(typeof(TextBlock));
            Binding binding1 = new Binding("RoleInstanceId");
            
            cellTemplateFactory1.SetBinding(TextBlock.TextProperty, binding1);

            DataTemplate defaultCellTemplate1 = new DataTemplate();
            defaultCellTemplate1.VisualTree = cellTemplateFactory1;
            //column.CellTemplate = defaultCellTemplate;
            
            GridViewColumn AzureRoleColumn = new GridViewColumn();
            AzureRoleColumn.Header = "Azure Roles";            
            AzureRoleColumn.HeaderTemplate = (DataTemplate)this.FindResource("RoleHeaderTemplate");
            //Binding b = new Binding("RoleInstanceId");
            AzureRoleColumn.CellTemplate = defaultCellTemplate1;

            configGrid.Columns.Add(AzureRoleColumn);
            int i = 0;
            foreach (int confkey in AzureMonInstanceContext.ConfigCountersets.CtrSets.Keys)
            {
                GridViewColumn column = new GridViewColumn();
                column.Header = "Counter Set - " + confkey;
                FrameworkElementFactory cellTemplateFactory = new FrameworkElementFactory(typeof(CheckBox));
                string str = "IsChecked[" + i + "]";
                Binding binding = new Binding(str);
                //binding.Path = new PropertyPath("RoleInstanceId", null);
                i++;
                //binding.Source = AzureMonInstanceContext.ConfigCountersets.CtrSets[confkey];
                cellTemplateFactory.SetBinding(CheckBox.IsCheckedProperty, binding);
                
                //IsChecked chkBoxCheck = new IsChecked(AzureMonInstanceContext.ConfigCountersets.CtrSets[confkey].IsChecked);
                
                RoutedEventHandler checkHandler = new RoutedEventHandler(AzureMonInstanceContext.ConfigCountersets.CtrSets[confkey].SelectionChanged);
                RoutedEventHandler uncheckHandler = new RoutedEventHandler(AzureMonInstanceContext.ConfigCountersets.CtrSets[confkey].SelectionChanged);
                cellTemplateFactory.AddHandler(CheckBox.CheckedEvent, checkHandler, true);
                cellTemplateFactory.AddHandler(CheckBox.UncheckedEvent, uncheckHandler, true);
                
                //cellTemplateFactory.SetValue(CheckBox.IsCheckedProperty, chkBoxCheck);                

                DataTemplate defaultCellTemplate = new DataTemplate();
                defaultCellTemplate.VisualTree = cellTemplateFactory;
                column.CellTemplate = defaultCellTemplate;

                DataTemplate htemplate = (DataTemplate)this.FindResource("myHeaderTemplate");

                
                 
                //try

               /* String headerXaml = @"<DataTemplate x:Class=""MindTree.PerfWorkbench.Azure.Monitor.AzMonConfig"" xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">" +
            @"<StackPanel>" +
                @"<TextBlock Name=""columnName"" Height=""15"" Width=""60"">CounterSet</TextBlock>" +
               @"<ToolBar Height=""18"" Name=""AzureMonToolBar"" Width=""100"" Margin=""6,2.5,5,0"" >" +
                    @"<Button Height=""15"" Width=""31"" >" +
                        @"<Image Name=""imgEditCounters"" Source=""icons\globe_32.png"" Height=""10"" Width=""22"" ToolTip=""View Counters"" MouseDown=""imgEditCounters_MouseDown"" />" +
                    @"</Button>" +
                @"</ToolBar>" +
            @"</StackPanel>" +
            @"</DataTemplate>";
                DataTemplate t = (DataTemplate)XamlReader.Parse(headerXaml);*/
                //Binding b = new Binding();
                //b.Source = AzureMonInstanceContext.ConfigCountersets.CtrSets[confkey];
                //column.DisplayMemberBinding = b;

                FrameworkElementFactory stckPanel = GetColumnHeaderTemplate(AzureMonInstanceContext.ConfigCountersets.CtrSets[confkey]);
                DataTemplate colHeader =new DataTemplate();
                colHeader.VisualTree = stckPanel;


                //try

                //Binding bn = new Binding();
                //bn.Source = AzureMonInstanceContext.ConfigCountersets.CtrSets[confkey];
                //GridViewColumnHeader head = new GridViewColumnHeader();
                //head.SetBinding(GridViewColumnHeader.ContentProperty, bn);
                //head. = htemplate;
                //head.SetBinding(
                
                //cellTemplateFactory.SetBinding(, bn);
                //column.HeaderTemplate = htemplate;
                column.HeaderTemplate = colHeader;
                

                //this.FindVisualChild<ContentPresenter>(column);
                configGrid.Columns.Add(column);
                  // htemplate.FindName("imgEditCounters",column
            }

                        
            this.ConfigurationList.View = configGrid;
            this.ConfigurationList.IsSynchronizedWithCurrentItem = true;
            this.ConfigurationList.Items.Clear();

            AzureAppDeployment app = new AzureAppDeployment(AzureMonInstanceContext.AzureApp.AppDeployment[0]);

            /*ConfigurationList.ItemsSource = from roles in AzureMonInstanceContext.AzureApp.AppDeployment[0].Roles
                                            select roles.Instances ;*/
            //System.Collections.Generic.IEnumerable<AzureRoleInstance> l = from roles in app.Roles
            //                                                              from instances in roles.Instances
            //                                                              select instances;
            //List<AzureRoleInstance> obj = l.ToList();

            ConfigurationList.ItemsSource = from roles in app.Roles
                                            from instances in roles.Instances
                                            select instances;
             /*foreach(AzureRole rl in AzureMonInstanceContext.AzureApp.AppDeployment[0].Roles)
             {
                 //foreach (AzureRoleInstance inst in rl.Instances)
                 //{
                 ConfigurationList.Items.Add(rl.Instances);
                 //}
             }*/
        }


        /// <summary>
        /// Dynamically Create column header template based on the unique counter sets available
        /// </summary>
        /// <param name="paramCntrSet">CounterSet object</param>
        /// <returns>Column header template as FrameworkHeaderFactory</returns>
        public FrameworkElementFactory GetColumnHeaderTemplate(CounterSet paramCntrSet)
        {
            FrameworkElementFactory stackPanel = new FrameworkElementFactory(typeof(StackPanel));

            FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock));

            FrameworkElementFactory toolBar = new FrameworkElementFactory(typeof(ToolBar));

            FrameworkElementFactory button = new FrameworkElementFactory(typeof(Button));

            FrameworkElementFactory image = new FrameworkElementFactory(typeof(Image));

            image.SetValue(Image.NameProperty, "imgEditCounters");
            ImageSourceConverter c = new ImageSourceConverter();
            
            //BitmapImage bi = new BitmapImage();
            //bi.BeginInit();
            //bi.UriSource = new Uri(@"icons\globe_32.png",UriKind.Relative);
            //bi.EndInit();

            try
            {
                image.SetValue(Image.SourceProperty, c.ConvertFromString(@"icons\globe_32.png"));
                
            }
            catch (Exception ex)
            {
                
            }
            image.SetValue(Image.HeightProperty, 15.0);
            image.SetValue(Image.WidthProperty, 22.0);
            image.SetValue(Image.ToolTipProperty,"View Counters");
            
            //RoutedEventHandler imgMouseDownEvent = new RoutedEventHandler(this.imgEditCounters_MouseDown);
            image.AddHandler(Image.MouseDownEvent, new MouseButtonEventHandler
                (this.imgEditCounters_MouseDown), true);
            
            Binding srcBinding = new Binding();
            srcBinding.Source = paramCntrSet;
            image.SetBinding(Image.TagProperty,srcBinding);
            

            button.SetValue(Button.WidthProperty,22.0);
            button.SetValue(Button.HeightProperty, 15.0);


            toolBar.SetValue(ToolBar.HeightProperty, 18.0);
            toolBar.SetValue(ToolBar.WidthProperty, 100.0);
            toolBar.SetValue(ToolBar.NameProperty,"AzureMonToolBar");
            toolBar.SetValue(ToolBar.MarginProperty, new Thickness(6,2.5,5,0));


            textBlock.SetValue(TextBlock.TextProperty, "CounterSet - "+ paramCntrSet.Index);
            textBlock.SetValue(TextBlock.NameProperty,"columnName");
            textBlock.SetValue(TextBlock.HeightProperty,15.0);
            textBlock.SetValue(TextBlock.WidthProperty,60.0);
            
            
            button.AppendChild(image);
            toolBar.AppendChild(button);

            stackPanel.AppendChild(textBlock);
            stackPanel.AppendChild(toolBar);

            return stackPanel;

        } 



        private void Image_MouseDown(object sender, MouseButtonEventArgs e)
        {

            CounterSet cntrSet = new CounterSet(new List<PerfCounter>());
            cntrSet.Index = AzureMonInstanceContext.ConfigCountersets.CtrSets.Keys.Max() + 1;
            AzureMonInstanceContext.ConfigCountersets.CtrSets.Add(AzureMonInstanceContext.ConfigCountersets.CtrSets.Keys.Max()+1, cntrSet);
            //newCounterSetList.Add(cntrSet);
            foreach (AzureRole role in AzureMonInstanceContext.AzureApp.AppDeployment[0].Roles)
            {
                foreach (AzureRoleInstance instance in role.Instances)
                {
                    instance.IsChecked.Add(false);
                }
            }
            #region Previous Code  14th July
            /*  Previous Code  14th July
            GridViewColumn column = new GridViewColumn();
            column.Header = "Counter Set - " + AzureMonInstanceContext.ConfigCountersets.CtrSets.Count;
            FrameworkElementFactory cellTemplateFactory = new FrameworkElementFactory(typeof(CheckBox));
            string str = "IsChecked[" + AzureMonInstanceContext.ConfigCountersets.CtrSets.Keys.Max() + "]";            
            Binding binding = new Binding(str);
            cellTemplateFactory.SetBinding(CheckBox.IsCheckedProperty, binding);
            DataTemplate defaultCellTemplate = new DataTemplate();
            defaultCellTemplate.VisualTree = cellTemplateFactory;
            column.CellTemplate = defaultCellTemplate;
            column.HeaderTemplate = (DataTemplate)this.FindResource("myHeaderTemplate");
            configGrid.Columns.Add(column);
            */
            #endregion

            //Start: Doing it on 14th

            GridViewColumn column1 = new GridViewColumn();
            column1.Header = "Counter Set - " + AzureMonInstanceContext.ConfigCountersets.CtrSets.Count; 
            FrameworkElementFactory cellTemplateFactory1 = new FrameworkElementFactory(typeof(CheckBox));
            string str1 = "IsChecked[" + AzureMonInstanceContext.ConfigCountersets.CtrSets.Keys.Max() + "]";
            Binding binding1 = new Binding(str1);
            //binding.Path = new PropertyPath("RoleInstanceId", null);
            //i++;
            //binding.Source = AzureMonInstanceContext.ConfigCountersets.CtrSets[confkey];
            cellTemplateFactory1.SetBinding(CheckBox.IsCheckedProperty, binding1);

            //IsChecked chkBoxCheck = new IsChecked(AzureMonInstanceContext.ConfigCountersets.CtrSets[confkey].IsChecked);

            RoutedEventHandler checkHandler = new RoutedEventHandler(AzureMonInstanceContext.ConfigCountersets.CtrSets[AzureMonInstanceContext.ConfigCountersets.CtrSets.Keys.Max()].SelectionChanged);
            RoutedEventHandler uncheckHandler = new RoutedEventHandler(AzureMonInstanceContext.ConfigCountersets.CtrSets[AzureMonInstanceContext.ConfigCountersets.CtrSets.Keys.Max()].SelectionChanged);
            cellTemplateFactory1.AddHandler(CheckBox.CheckedEvent, checkHandler, true);
            cellTemplateFactory1.AddHandler(CheckBox.UncheckedEvent, uncheckHandler, true);

            //cellTemplateFactory.SetValue(CheckBox.IsCheckedProperty, chkBoxCheck);                

            DataTemplate defaultCellTemplate1 = new DataTemplate();
            defaultCellTemplate1.VisualTree = cellTemplateFactory1;
            column1.CellTemplate = defaultCellTemplate1;

            DataTemplate htemplate = (DataTemplate)this.FindResource("myHeaderTemplate");

            FrameworkElementFactory stckPanel = GetColumnHeaderTemplate(AzureMonInstanceContext.ConfigCountersets.CtrSets[AzureMonInstanceContext.ConfigCountersets.CtrSets.Keys.Max()]);
            DataTemplate colHeader = new DataTemplate();
            colHeader.VisualTree = stckPanel;

            column1.HeaderTemplate = colHeader;

            configGrid.Columns.Add(column1);

            //End: Doing it on 14th

        }


        /// <summary>
        /// Save configuration
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {            
            // 14th foreach (List<AzureRoleInstance> inst in ConfigurationList.Items)
            //14th{

            if (!String.IsNullOrEmpty(cmbBoxInterval.Text.Trim()))
            {
                try
                {
                    AzureAppDeployment.MonitoringInterval = Int32.Parse(cmbBoxInterval.Text.Trim());
                }
                catch (Exception ex)
                {

                }
            }
                foreach (AzureRoleInstance instance in ConfigurationList.Items)
                {
                    AzureRoleInstance role = AzureMonInstanceContext.AzureApp.AppDeployment[0].GetRoleInstanceByInstanceId(instance.RoleInstanceId);
                    role.CounterSetIndex = instance.CounterSetIndex;
                    for(int i=0; i < role.IsChecked.Count; i++)
                    {
                        if (role.CounterSetIndex.Contains(i))
                        {
                            role.IsChecked[i] = true;
                        }
                        else
                        {
                            role.IsChecked[i] = false;
                        }
                    }
                }
            
            //14th}            
            IsOK = true;
            //AzureMonInstanceContext.AzureApp.AppDeployment[0].Roles
            //foreach (CounterSet cntrSet in newCounterSetList)
            //{
            //    AzureMonInstanceContext.ConfigCountersets.CtrSets.Add(AzureMonInstanceContext.ConfigCountersets.CtrSets.Keys.Max() + 1, cntrSet);
            //}
            Close();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            IsOK = false;
            Close();
        }     


        /// <summary>
        /// Edit Performance Counters
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgEditCounters_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Image img = sender as Image;            
            ConfigureMonCounters MonCountersDialog = new ConfigureMonCounters(((CounterSet)img.Tag).Counters);
            MonCountersDialog.ShowDialog();
            if (MonCountersDialog.IsOK)
            {
                isModified = true;
                ((CounterSet)img.Tag).Counters = MonCountersDialog.SelectedCounters;
                return;
            }
            else
            {
                return;
            }
            
        }
    }
}
